#include "cgic.h"
#include <glib.h>
#include "global.h"
#include "MsgUtil.h"

int cgiMain(){
    //1 获取gatewayIp和location
    char gatewayIp[256];
    cgiFormString("gatewayIp",gatewayIp,256);
    char location[256];
    cgiFormString("location",location,256);

    //2写入devInfo.ini  [config] gatewayIp  location
    //2.1 获取要保存文件路径
    GKeyFile *configKeyFile = g_key_file_new();

    if(!g_key_file_load_from_file(configKeyFile,"./config.ini",G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return -1;
    }
    gchar *deviceInfoPath = g_key_file_get_string(configKeyFile,"config","deviceInfoPath",NULL);
    g_key_file_free(configKeyFile);

    //2.2 把信息写到那个文件中
    GKeyFile *deviceInfoFile = g_key_file_new();
    g_key_file_set_string(deviceInfoFile,"config","gatewayIp",gatewayIp);
    g_key_file_set_string(deviceInfoFile,"config","location",location);
    //把设置的值保持到某个文件中
    g_key_file_save_to_file(deviceInfoFile,deviceInfoPath,NULL);
    g_key_file_free(deviceInfoFile);
    //获取mqid
    int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);
    if (mqId==-1)
    {
       perror("get msg queue error!");
       return -1;
    }
    Message msg = {
        .type=1,
        .text = "register ads"
    };
    int sendSize = sendMsg(mqId,&msg,MSG_SIZE);
     if (sendSize==-1)
    {
      cgiHeaderContentType("text/html");
      //输出到客户端浏览器
      fprintf(cgiOut,"<html><head><title>响应</title></head><body>");
      fprintf(cgiOut,"false!");
      fprintf(cgiOut,"</body></html>");
      return -1;
    }
   //4 响应一个配置成功返回给界面
    //告诉浏览器，是一个html文档
    cgiHeaderContentType("text/html");
    //输出到客户端浏览器
    fprintf(cgiOut,"<html><head><title>响应</title></head><body>");
    fprintf(cgiOut,"success!");
    fprintf(cgiOut,"</body></html>");

    return 0;

}